package com.example.demo.control;

import com.example.demo.others.git.GitUtil;
import com.example.demo.others.jenkins.Jenkins;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by Administrator on 2017-6-9.
 */
@RestController
@RequestMapping
public class LoginControl {

    Logger logger = LoggerFactory.getLogger(LoginControl.class);



    @RequestMapping("/login")
    public String index(HttpServletRequest request, String gitname, String gitpwd, String jenkinname, String jenkinspwd
            , HttpServletResponse response) {

        if (StringUtils.isBlank(gitname) || StringUtils.isBlank(gitpwd)) {
            return "git name pw bu neng weikong";
        }
        if (StringUtils.isBlank(jenkinname) || StringUtils.isBlank(jenkinspwd)) {
            return "jenkins name pw bu neng weikong";
        }


        request.getSession().setAttribute("gitname", gitname);
        request.getSession().setAttribute("gitpwd", gitpwd);
        request.getSession().setAttribute("jenkinname", jenkinname);
        request.getSession().setAttribute("jenkinspwd", jenkinspwd);



        cookie("gitname", gitname, response);
        cookie("gitpwd", gitpwd, response);
        cookie("jenkinname", jenkinname, response);
        cookie("jenkinspwd", jenkinspwd, response);

        String login = Jenkins.addJenkins(jenkinname, jenkinspwd);
        if (StringUtils.isBlank(login)) {
            GitUtil.addCre(gitname, gitpwd);
            return "success";
        } else
            return login;


    }

    private void cookie(String name, String val, HttpServletResponse response) {
        Cookie cookie = new Cookie(name, val);
        cookie.setMaxAge(Integer.MAX_VALUE);
        cookie.setPath("/");
//        cookie.set
        response.addCookie(cookie);
    }


}
